using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Super.RadarMap
{

	/// <summary>
	/// 雷达图工具
	/// </summary>
	[RequireComponent(typeof(CanvasRenderer))]
	public class RadarMap : Graphic
	{
		//最长长度
		public float length;
		//偏转角度
		public float offsetRotate;
		//数据列表
		[Range(0, 1)]
		public List<float> points;

		/// <summary>
		/// 绘制雷达图，首次绘制调用
		/// </summary>
		/// <param name="points"></param>
		/// <param name="length"></param>
		/// <param name="offsetRotate"></param>
		public void DrawMap(List<float> points, float length, float offsetRotate)
		{
			this.points = new List<float>(points);
			this.length = length;
			this.offsetRotate = offsetRotate;
		}

		/// <summary>
		/// 雷达图数据刷新时调用
		/// </summary>
		/// <param name="points"></param>
		public void Refresh(List<float> points)
		{
			this.points = new List<float>(points);
		}
		protected override void OnPopulateMesh(VertexHelper vh)
		{
			vh.Clear();
			for (int i = 0; i < points.Count; i++)
			{
				UIVertex[] vertexs = GetVertexs(points.Count, points, i);
				vh.AddUIVertexQuad(vertexs);
			}

		}

		private UIVertex[] GetVertexs(int count, List<float> points, int index)
		{
			UIVertex[] uIVertexs = new UIVertex[4];
			index = GetIndex(count, index - 1);
			for (int i = 0; i < 4; i++)
			{
				uIVertexs[i] = new UIVertex();
				uIVertexs[i].position = i == 0 ? new Vector2(0, 0) : GetPos(count, points[index], index);
				uIVertexs[i].color = color;
				index = i == 0 ? index : GetIndex(count, index + 1);
			}
			return uIVertexs;
		}

		private Vector2 GetPos(int count, float point, int index)
		{
			float rotation = offsetRotate + (360f / count) * index;
			float deg = Mathf.Deg2Rad * rotation;
			float x = length * point * Mathf.Sin(deg);
			float y = length * point * Mathf.Cos(deg);
			return new Vector2(x, y);
		}

		private int GetIndex(int count, int index)
		{
			if (index < 0)
			{
				return count - 1;
			}
			else if (index > count - 1)
			{
				return 0;
			}
			return index;
		}
	}

}
